/**
 * 计算使用情况的工具
 * @author slf
 * @date 2021/8/10
 */
public class UsedUtils {
    private static final Runtime s_runtime =Runtime.getRuntime ();
    private static  long usedMem1,usedMem2;
    private static long memStart,memEnd;
    private static long timeStart,timeEnd;

    private static long usedMemory (){
        return s_runtime.totalMemory () - s_runtime.freeMemory ();
    }

    private static void runGC ()
    {
         usedMem1 = usedMemory ();
         usedMem2 = Long.MAX_VALUE;
        for (int i = 0; (usedMem1 < usedMem2) && (i < 500); ++ i)
        {
            s_runtime.runFinalization ();
            s_runtime.gc ();
            Thread.currentThread ().yield ();
            usedMem2 = usedMem1;
            usedMem1 = usedMemory ();
        }
    }
    public static void start(){
        runGC();
        memStart = usedMemory();
        timeStart = System.currentTimeMillis();
    }
    public static void end(int count){
        timeEnd = System.currentTimeMillis();
        runGC();
        memEnd = usedMemory();
        if(count==0){
            System.out.println("耗时(ms)："+(timeEnd-timeStart));
            System.out.println("耗内存(b)："+(memEnd-memStart));
        }else{
            System.out.println("每次耗时(ms)："+(timeEnd-timeStart)/(double)count);
            System.out.println("每次耗内存(b)："+(memEnd-memStart)/(double)count);
        }

    }
    public static void end(){
        end(1);
    }
}
